#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include "Data_flattening.h"
#include "../matrix_operations/matrix_operations.h" 
#define NUM_IMAGES 10
#define IMG_ROWS 28
#define IMG_COLS 28

// 读取 PGM 图像为 28x28 的 double 矩阵
bool pgm_to_matrix(const char *file_path, int rows, int cols, double matrix[rows][cols])
{
    FILE *fp = fopen(file_path, "rb");
    if (!fp)
    {
        fprintf(stderr, "Failed to open file: %s\n", file_path);
        return false;
    }

    char magic[3];
    fscanf(fp, "%2s", magic);
    if (strcmp(magic, "P5") != 0)
    {
        fprintf(stderr, "Invalid PGM format in: %s\n", file_path);
        fclose(fp);
        return false;
    }

    int width, height, max_val;
    fscanf(fp, "%d %d %d", &width, &height, &max_val);
    fgetc(fp); // 跳过换行

    if (width != cols || height != rows)
    {
        fprintf(stderr, "Image size must be %dx%d, got %dx%d\n", cols, rows, width, height);
        fclose(fp);
        return false;
    }

    for (int i = 0; i < rows; ++i)
    {
        for (int j = 0; j < cols; ++j)
        {
            unsigned char pixel = fgetc(fp);
            matrix[i][j] = (double)pixel;
        }
    }

    fclose(fp);
    return true;
}

int main()
{
    double matrices[NUM_IMAGES][IMG_ROWS][IMG_COLS];

    for (int idx = 0; idx < NUM_IMAGES; ++idx)
    {
        char filename[64];
        snprintf(filename, sizeof(filename), "../input_files/%d.pgm", idx);

        if (!pgm_to_matrix(filename, IMG_ROWS, IMG_COLS, matrices[idx]))
        {
            fprintf(stderr, "Failed to process %s\n", filename);
            return EXIT_FAILURE;
        }

        printf("Loaded %s successfully.\n", filename);
    }

    // 示例：打印第0张图像的前5行前5列
    printf("\nSample values from 0.pgm:\n");
    for (int i = 0; i < 5; ++i)
    {
        for (int j = 0; j < 5; ++j)
        {
            printf("%4.0f ", matrices[0][i][j]);
        }
        printf("\n");
    }

    return 0;
}
